contexts = {}

class window.Context
  constructor : (@name, w, h) ->
    w ?= 800
    h ?= 400

    contexts[@name] = @
    @canvas = document.createElement "canvas"
    document.body.appendChild @canvas
    @gl = @canvas.getContext "webgl", {premultipliedAlpha: false, alpha:false}  || @canvas.getContext "experimental-webgl", {premultipliedAlpha: false, alpha:false}

    @gl.enable @gl.BLEND
    @gl.blendFunc @gl.SRC_ALPHA, @gl.ONE_MINUS_SRC_ALPHA

    @gl.clearColor(1,1,1,1);
    @gl.clear(@gl.COLOR_BUFFER_BIT);
    @gl.pixelStorei @gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false

    @gl.colorMask(true, true, true, false); 
    
    @setWidth w
    @setHeight h


    @clearColor 0.0, 0.0, 0.0, 1.0
    @clear()

  clearColor : (x, y, z, w) -> 
    x ?= 1.0
    y ?= x
    z ?= y
    w ?= 1.0

    @gl.clearColor x, y, z, w
  

  getCanvas : () -> @canvas
  screen : () ->
    {
      x : 1.0 / (@canvas.width / 2.0)
      y : -1.0 / (@canvas.height / 2.0)
    }

  setWidth : (w) -> 
    @canvas.width = w
    @gl.viewport 0, 0, @canvas.width, @canvas.height

  setHeight : (h) -> 
    @canvas.height = h
    @gl.viewport 0, 0, @canvas.width, @canvas.height

  clear : () -> @gl.clear @gl.COLOR_BUFFER_BIT | @gl.DEPTH_BUFFER_BIT

  Texture : () -> new window.Texture @
  Program : () -> new window.Program @
  MeshBuffer : (defaultSize) -> new window.MeshBuffer @, defaultSize
  SpriteRender : () -> new window.SpriteRender @
  Font437 : () -> new window.Font437 @



window.getContext = (name) -> contexts[name]